package com.longyb.mylive.client;

import com.longyb.mylive.server.rtmp.Tools;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author longyubo 2019年12月30日 下午6:09:11
 **/
@Slf4j
public class HandShakeEncoder extends ByteToMessageDecoder {
	private  static int HANDSHAKE_LENGTH = 1536;
	private static int VERSION_LENGTH = 1;

	private transient boolean sendC0C1=false;

//	private transient boolean recvS1S2=false;

	private transient boolean sendC2=false;

	private transient  byte[] s1=new byte[HANDSHAKE_LENGTH];
//	private transient boolean recvS2=false;
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {


		if (sendC0C1) {
			if (in.readableBytes() < VERSION_LENGTH + HANDSHAKE_LENGTH) {
				return;
			}
			in.readByte();
			in.readBytes(s1);
			log.info("接收S1，S2");
//			recvS1S2=true;
			//写c2
			ByteBuf c2=Unpooled.buffer(HANDSHAKE_LENGTH);
			c2.writeBytes(s1);
			ctx.writeAndFlush(c2);
			log.info("发送C2");
			sendC2=true;
		}
		if (sendC2) {
			if (in.readableBytes() < HANDSHAKE_LENGTH) {
				return;
			}
			in.readBytes(HANDSHAKE_LENGTH);
//			recvS2=true;
			log.info("接收S2");
			ctx.fireUserEventTriggered("handlShake");
			ctx.channel().pipeline().remove(this);

		}



	}


	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		//直接发送c0,c1
		ByteBuf buf= Unpooled.buffer(VERSION_LENGTH + HANDSHAKE_LENGTH);
		//c0
		buf.writeByte(ClientHandStatus.C0);


		/**
		 * 每个客户端不一样
		 * 0x0D, 0x0E, 0x0A, 0x0D 复杂握手版本
		 c1s1 schema0 ：key在前，digest在后
		 time: 4 bytes
		 version: 4 bytes
		 key: 764 bytes
		 digest: 764 bytes


		 c1s1 schema1：digest在前，key在后
		 time: 4 bytes
		 version: 4 bytes
		 digest: 764 bytes
		 key: 764 bytes
		 */
		//c1 timestamp（4bytes）+ Version（4bytes）+ （复杂二进制串）1526bytes
		buf.writeInt(0); //timestamp 简单握手全是4byte=0
		buf.writeInt(0); //version 简单握手全是4byte=0
		buf.writeBytes(Tools.generateRandomData(1536 - 8));
		ctx.writeAndFlush(buf);
		sendC0C1=true;
		log.info("发送C1，C2");


	}
}
